#include "stopwatch.hpp"

Stopwatch::Stopwatch() {
  running=false;
#ifdef _WIN32
  QueryPerformanceCounter(&startTime);
#else
  gettimeofday(&startTime,NULL);
#endif
  endTime=startTime;
}

Stopwatch::~Stopwatch() {
}

void Stopwatch::start() {
  running=true;
#ifdef _WIN32
  QueryPerformanceCounter(&startTime);
#else
  gettimeofday(&startTime,NULL);
#endif
}

void Stopwatch::stop() {
#ifdef _WIN32
  QueryPerformanceCounter(&endTime);
#else
  gettimeofday(&endTime,NULL);
#endif
  running=false;
}

double Stopwatch::secondsElapsed() {
  if (running) {
    stop();
  }
#ifdef _WIN32
  LARGE_INTEGER time;
  time.QuadPart=endTime.QuadPart-startTime.QuadPart;
  LARGE_INTEGER frequency;
  QueryPerformanceFrequency(&frequency) ;
  return ((double)time->QuadPart/(double)frequency.QuadPart) ;
#else
  return (endTime.tv_sec+(endTime.tv_usec/1000000.0))-(startTime.tv_sec+(startTime.tv_usec/1000000.0));
#endif
}

void Stopwatch::print(const char* msg) {
  printf("%s in %f seconds.\n",msg,secondsElapsed());
}

char * Stopwatch::toString(const char* msg) {
  sprintf(buffer,"%s in %f seconds.\n",msg,secondsElapsed());
  return buffer;
}
